from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.utils import timezone
from .models import Order, OrderItem
from .serializers import OrderSerializer, OrderItemSerializer
from users.permissions import PurchaserPermission, SalesmanPermission, DeliverymanPermission, CustomerPermission, IsAdmin

class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_permissions(self):
        if self.action in ['create']:
            return [CustomerPermission()|PurchaserPermission()|SalesmanPermission()|IsAdmin()]
        elif self.action in ['update', 'partial_update', 'destroy']:
            return [SalesmanPermission()|PurchaserPermission()|IsAdmin()]
        return [permissions.IsAuthenticated()]

    def get_queryset(self):
        user = self.request.user
        if user.role == 'admin':
            return Order.objects.all()
        elif user.role == 'purchaser':
            return Order.objects.filter(customer=user)
        elif user.role == 'salesman':
            return Order.objects.all()
        elif user.role == 'customer':
            return Order.objects.filter(customer=user)
        elif user.role == 'deliveryman':
            return Order.objects.filter(delivery__deliveryman=user)
        return Order.objects.none()

    @action(detail=True, methods=['post'])
    def update_status(self, request, pk=None):
        """更新订单状态"""
        order = self.get_object()
        new_status = request.data.get('status')
        
        if new_status not in dict(Order.STATUS_CHOICES):
            return Response(
                {'detail': '无效的状态'},
                status=status.HTTP_400_BAD_REQUEST
            )
            
        order.status = new_status
        if new_status == 'completed':
            order.completed_at = timezone.now()
        order.save()
        
        return Response(self.get_serializer(order).data)

    @action(detail=True, methods=['get'])
    def items(self, request, pk=None):
        """获取订单项"""
        order = self.get_object()
        items = order.items.all()
        serializer = OrderItemSerializer(items, many=True)
        return Response(serializer.data)

class OrderItemViewSet(viewsets.ModelViewSet):
    queryset = OrderItem.objects.all()
    serializer_class = OrderItemSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_permissions(self):
        if self.action in ['create', 'update', 'partial_update', 'destroy']:
            return [SalesmanPermission()|PurchaserPermission()|IsAdmin()]
        return [permissions.IsAuthenticated()]

    def get_queryset(self):
        user = self.request.user
        if user.role == 'admin':
            return OrderItem.objects.all()
        elif user.role == 'salesman':
            return OrderItem.objects.all()
        elif user.role == 'purchaser':
            return OrderItem.objects.all()
        elif user.role == 'customer':
            return OrderItem.objects.filter(order__customer=user)
        elif user.role == 'deliveryman':
            return OrderItem.objects.filter(order__delivery__deliveryman=user)
        return OrderItem.objects.none() 